//
//  HXAddJobRecViewController.m
//  KD
//
//  Created by ifly on 16/7/8.
//  Copyright © 2016年 Whx. All rights reserved.
//

#import "HXAddJobRecViewController.h"
#import "HXUpDataImageModel.h"
#import "UIButton+WebCache.h"

#import "HXGroupJobTableViewController.h"
#import "HXIflyJobRecordDetailsTableViewController.h"

#import "CCLocationManager.h"

@interface HXAddJobRecViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,BMKGeoCodeSearchDelegate,BMKLocationServiceDelegate,BMKMapViewDelegate,UITextViewDelegate>
@property (weak, nonatomic) IBOutlet UILabel *dateLabel;
@property (weak, nonatomic) IBOutlet UITextView *jobTextView;
@property (weak, nonatomic) IBOutlet UILabel *placeHoldLabel;

@property(nonatomic,strong)UILongPressGestureRecognizer * longPress;
@property (nonatomic,strong) UIScrollView *photoScrollView;
@property(nonatomic,strong) HXUpDataImageModel *dict;
@property (nonatomic,assign) NSInteger num;
@property (nonatomic,strong) UIButton *photoBtn;
@property (nonatomic,strong) NSMutableArray *phothMuArray;

@property (nonatomic,copy) NSString * groupId;
@property(nonatomic,strong)NSString * locationStr;
@property (nonatomic,strong) NSMutableArray *photoFilePathArr;
@property (nonatomic,copy) NSString * messageId;
/**
 汇报详情Model
 */
@property (nonatomic,strong) HXReadDayWorkOrCommentDetailsModel * headerDetaileModel;
/**
 图片数组
 */
@property (nonatomic,strong) NSArray <HXReadDayWorkOrCommentPiclistModel *>* piclistArr;

@property (nonatomic,strong) NSMutableArray *dataArr;

@end

@implementation HXAddJobRecViewController

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    if (self.type == AddJobRecordType) {
        
        [self.addSuperVC loadCreateDataMethod];
    }else if(self.type == ChangeJobRecordType){
        
        //        [self.changeSuperVC loadCreateData];
    }
//    self.longPress = nil;
//    self.photoScrollView = nil;
//    self.dict = nil;
//    self.photoBtn = nil;
//    self.phothMuArray = nil;
//    self.groupId = nil;
//    self.locationStr = nil;
//    self.photoFilePathArr = nil;
//    self.messageId = nil;
}


/**
 重写init方法 1.需要MessageID
 */
-(instancetype)initWithMessageID:(NSString *)MessageID{
    
    if ([super init]) {
        
        self.messageId = MessageID;
    }
    
    return self;
}



/**
 重写init方法 1.需要 群组ID
 */
-(instancetype)initWithGroupId:(NSString *)groupId{

    if ([super init]) {
        
        self.groupId = groupId;
    }
    
    return self;
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [[CCLocationManager shareLocation] getAddress:^(NSString *addressString) {
        
        self.locationStr = addressString;
    }];
    
    self.jobTextView.layer.borderColor = [UIColor blackColor].CGColor;
    self.jobTextView.layer.borderWidth = 1.0;
    self.jobTextView.delegate = self;
    if (self.type == AddJobRecordType) {
        self.jobTextView.text = @"今日工作:\n\n遇到问题:\n\n明日计划:";
        NSLog(@"-----------------%ld",(unsigned long)self.jobTextView.text.length);
        [self getNetTime];
    }
    if (self.type == ChangeJobRecordType) {
        self.dateLabel.text = self.datWorkTime;
        self.dateLabel.textAlignment = NSTextAlignmentRight;
    }
    [self changeNavigationBar];
    [self addPhoto];
    
    [self changeDayWork];
}

/**
 协议方法
 */
-(void)textViewDidChange:(UITextView *)textView {
    
    if (self.jobTextView.text.length == 0) {
        self.jobTextView.text = @"今日工作:\n\n遇到问题:\n\n明日计划:";
    }
}

/**
 修改日报
 */
-(void)changeDayWork {
    if (self.type == ChangeJobRecordType) {
        
        self.jobTextView.text = self.dayWorkCon;
        
        for (int i = 0; i<self.getPhotoArr.count; i++) {
            
            NSString * path = self.getPhotoArr[i].Pic_Path;
            
            [self.photoFilePathArr addObject:path];
        }
        [self getPhotoInScrollView];
    }
}
/**
 修改scrollView
 */
-(void)getPhotoInScrollView {
   
    for (int i = 0; i<self.photoFilePathArr.count; i++) {
        _photoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _photoBtn.tag = 1001 + i;
        _photoBtn.frame = CGRectMake(10 + 110 * (i + 1), 0, 100, 100);
        [_photoBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:self.photoFilePathArr[i]] forState:UIControlStateNormal];
        [_photoBtn addTarget:self action:@selector(photoBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        //_photoBtn.backgroundColor = [UIColor greenColor];
        [_photoScrollView addSubview:_photoBtn];
    }
    _photoScrollView.contentSize = CGSizeMake(110 * (self.photoFilePathArr.count + 1), 100);
//    _longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(pictureLongPress:)];
//    [_photoScrollView addGestureRecognizer:_longPress];
}


/**
 自定义导航啦按钮
 */
-(void)changeNavigationBar {
    
    if (self.type == AddJobRecordType) {
        self.navigationItem.title = @"写日报";
    }
    if (self.type == ChangeJobRecordType) {
        self.navigationItem.title = @"修改日报";
    }
    //右按钮
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(rightItemClick)];
    rightItem.tintColor = [UIColor orangeColor];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    //左按钮
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(leftItemClick)];
    self.navigationItem.leftBarButtonItem = leftItem;
}

/**
 获取网络时间
 */
-(void)getNetTime {
    [NetworkAPI getServerDateSuccess:^(HXServerDateModel *result) {
        if ([result.code isEqualToString:@"200"]) {
            self.dateLabel.text =  [NSString stringWithFormat:@"%@",result.ServerDate];
            self.dateLabel.textAlignment = NSTextAlignmentRight;
        }
    } failure:^(NSError *err) {
        [SVProgressHUD showErrorWithStatus:@"获取网络时间失败,请检查网络"];
    }];
}


/**
 添加照片
 */
-(void)addPhoto {
    _photoScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, self.jobTextView.y + self.jobTextView.height + 10, HXSCREEN_WIDTH, 100)];
    //_photoScrollView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:_photoScrollView];
    UIButton * addPhotoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addPhotoBtn.tag = 100;
    addPhotoBtn.frame = CGRectMake(10, 0, 100, 100);
    //addPhotoBtn.backgroundColor = [UIColor redColor];
    [addPhotoBtn setImage:[UIImage imageNamed:@"addimageshadow"] forState:UIControlStateNormal];
    [addPhotoBtn addTarget:self action:@selector(addPhotoBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_photoScrollView addSubview:addPhotoBtn];
    //长按手势
    _longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(pictureLongPress:)];
    [_photoScrollView addGestureRecognizer:_longPress];
}

/**
 上传数据
 */
-(void)loadCreateUpload{

    [SVProgressHUD showWithStatus:@"正在上传"];
    [NetworkAPI addDayWorkWithC_SendAdd:_locationStr
                      withC_SendGroupID:self.groupId
                          withC_Content:self.jobTextView.text
                       withPicListArray:self.photoFilePathArr
                                Success:^(HXBaseModel *result) {
                                    
                                    if ([result.code isEqualToString:@"200"]) {
                                        [SVProgressHUD showSuccessWithStatus:@"上传成功，正在返回..."];
                                        [self.navigationController popViewControllerAnimated:YES];
                                    }else if ([result.code isEqualToString:@"400"]) {
                                        [SVProgressHUD showErrorWithStatus:@"网络错误,请重试"];
                                    }else {
                                        [SVProgressHUD showErrorWithStatus:@"网络错误,请重试"];
                                    }
                                } failure:^(NSError *err) {
                                    [SVProgressHUD showErrorWithStatus:@"网络错误!"];
                                }];
    
    }

/**
 点击事件
 */
-(void)rightItemClick {
    
    if ([self.jobTextView.text containsString:@"今日工作"] && [self.jobTextView.text containsString:@"明日计划"] && self.jobTextView.text.length > 19) {
        
        if (self.type == AddJobRecordType) {
            
            if (self.locationStr == nil) {
                
                [LTAlertView showTitle:@"⚠️"
                               message:@"定位失败！确定提交日报？"
                          ButtonTitles:@[@"取消",@"确定"]
                            OnTapBlock:^(LTAlertView *alert, NSInteger num) {
                                if (num == 1) {
                                    
                                    self.locationStr = @"";
                                    
                                    [self loadCreateUpload];
                                }
                            }];
            }else{
                
                [self loadCreateUpload];
            }

        }else if(self.type == ChangeJobRecordType) {
            
            for (int i = 0; i<self.photoFilePathArr.count; i++) {
                NSDictionary * pathDic = @{
                                           @"Files_Path":self.photoFilePathArr[i]
                                           };
                [self.dataArr addObject:pathDic];
            }
            
            [NetworkAPI changeDayWorkWithDayWorkID:self.messageId
                                     WithC_Content:self.jobTextView.text
                                  withPicListArray:self.dataArr
                                           Success:^(HXBaseModel *result) {
                                               if ([result.code isEqualToString:@"200"]) {
                                                   [SVProgressHUD showSuccessWithStatus:@"上传成功，正在返回..."];
                                                   [self.navigationController popViewControllerAnimated:YES];
                                               }else if ([result.code isEqualToString:@"400"]) {
                                                   [SVProgressHUD showErrorWithStatus:@"网络错误,请重试"];
                                               }else {
                                                   [SVProgressHUD showErrorWithStatus:@"网络错误,请重试"];
                                               }
                                           } failure:^(NSError *err) {
                                               [SVProgressHUD showErrorWithStatus:@"网络错误!"];
                                           }];
        }
    }else {
   
        UIAlertController * alertCon = [UIAlertController alertControllerWithTitle:@"提示"
                                                                           message:@"请按照'今日工作:遇到问题:明日计划:格式填写'"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * alertAct = [UIAlertAction actionWithTitle:@"确定"
                                                            style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

        }];
        [alertCon addAction:alertAct];
        [self presentViewController:alertCon animated:YES completion:^{
        }];
    }
}
-(void)leftItemClick {
    //取消啊
   
    [self.navigationController popViewControllerAnimated:YES];
}
/**
 拍照选取照片
 */

-(void)addPhotoBtnClick {
    
    [self.jobTextView resignFirstResponder];
    
    CTActionSheet *actionSheet = [CTActionSheet actionSheetWithTitle:nil cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@"从相机相册选择" HandleBlock:^(int btnIndex) {
        if (btnIndex == 0) {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
                UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
                picker.delegate = self;
                picker.allowsEditing = YES;//设置可编辑
                picker.sourceType = sourceType;
                [self presentViewController:picker animated:YES completion:^{
                }];//进入照相界面
            }
        }else if (btnIndex == 1){
            UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
            if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
            }
            pickerImage.delegate = self;
            pickerImage.allowsEditing = YES;
            [self presentViewController:pickerImage animated:YES completion:^{
            }];
        }else{
        }
    }];
    UIWindow* window = [[[UIApplication sharedApplication] delegate] window];
    if ([window.subviews containsObject:self.view]) {
        [actionSheet showInView:self.view];
    } else {
        [actionSheet showInView:window];
    }

}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *originalImage =  (UIImage *) [info objectForKey:UIImagePickerControllerEditedImage];
    if(!originalImage){
        originalImage = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    [self sendUpImage:originalImage];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

/**
 上传照片
 */
-(void)sendUpImage:(UIImage *)image {
    
    NSData *imageData = UIImageJPEGRepresentation(image, 1);
    if  (imageData.length>300000){
        UIImage *image = [UIImage imageWithData:imageData];
        imageData = UIImageJPEGRepresentation(image, 0.005);
    }
    [self.phothMuArray addObject:image];
    if (self.type == AddJobRecordType) {
        [self setPhotoInScrollView];
    }
    //1。创建管理者对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObjectsFromArray:@[@"application/json", @"text/json",@"text/html", @"text/javascript", @"text/plain"]];
    [manager POST:[NSString stringWithFormat:@"%@/DayWork/SendFiles.ashx",API_HOST] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:imageData name:@"img" fileName:@"name" mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        _dict = [[HXUpDataImageModel alloc]initWithDictionary:responseObject error:nil];
        if ([_dict.code isEqualToString:@"200"]) {
            [SVProgressHUD showSuccessWithStatus:@"图片上传成功"];
            
            //图片网址_dict.FilePath
            NSDictionary * photoPath = @{
                                         @"Files_Path":_dict.FilePath
                                         };
            if (self.type == AddJobRecordType) {
                [self.photoFilePathArr addObject:photoPath];
            }
            if (self.type == ChangeJobRecordType) {
                [self.photoFilePathArr addObject:_dict.FilePath];
                [self getPhotoInScrollView];
            }
        }
        else{
            [SVProgressHUD showErrorWithStatus:@"图片上传失败"];
        }
       
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:@"图上传失败"];
    }];
}

/**
 设置scrollView
 */
-(void)setPhotoInScrollView {
    for (int i = 0; i<self.phothMuArray.count; i++) {
        _photoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _photoBtn.tag = 1001 + i;
        _photoBtn.frame = CGRectMake(10 + 110 * (i + 1), 0, 100, 100);
        [_photoBtn setImage:self.phothMuArray[i] forState:UIControlStateNormal];
        [_photoBtn addTarget:self action:@selector(photoBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        //_photoBtn.backgroundColor = [UIColor greenColor];
        [_photoScrollView addSubview:_photoBtn];
    }
    _photoScrollView.contentSize = CGSizeMake(110 * (self.phothMuArray.count + 1), 100);
}
-(void)photoBtnClick:(UIButton *)btn {
    
    NSLog(@"btn.tag-----------%ld",btn.tag);
}



-(void)pictureLongPress:(UILongPressGestureRecognizer *)longPress {
    
    NSMutableArray * arrayLast = [[NSMutableArray alloc] init];
    CGPoint point = [longPress locationInView:self.photoScrollView];
    NSString * strPoint =NSStringFromCGPoint(point);
    NSArray * array = [strPoint componentsSeparatedByString:@","];
    NSArray * arrayTwo = [array[0] componentsSeparatedByString:@"{"];
    for (int i = 0; i <= 20; i++) {
        if ([arrayTwo[1] intValue] > (110*i+10)) {
            [arrayLast addObject:[NSString stringWithFormat:@"%d",i]];
        }
    }
    NSString * removeIndexStr = [NSString stringWithFormat:@"%@",[arrayLast lastObject]];

    if (self.type == AddJobRecordType) {
        
        if ([removeIndexStr integerValue] > self.phothMuArray.count) {
            NSLog(@"揍你");
        }
        else {
            UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"是否删除照片"
                                                                                      message:@""
                                                                               preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction * cancelButton = [UIAlertAction actionWithTitle:@"取消"
                                                                    style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction *action) {
                                                                      NSLog(@"取消");
                                                                  }];
            UIAlertAction * creationBtn = [UIAlertAction actionWithTitle:@"删除"
                                                                   style:UIAlertActionStyleDestructive
                                                                 handler:^(UIAlertAction * _Nonnull action) {
                                                                     [_photoScrollView removeFromSuperview];
                                                                     _photoScrollView = nil;
                                                                     [self.phothMuArray removeObjectAtIndex:[removeIndexStr integerValue] - 1];
                                                                     if (_photoBtn.tag == 1000 + [removeIndexStr integerValue]) {
                                                                         [_photoBtn removeFromSuperview];
                                                                     }
                                                                     [self addPhoto];
                                                                     [self setPhotoInScrollView];
                                                                 }];
            [alertController addAction:cancelButton];
            [alertController addAction:creationBtn];
            [self presentViewController:alertController animated:YES completion:^{
                
            }];
        }
    }
    if (self.type == ChangeJobRecordType) {
        if ([removeIndexStr integerValue] > self.photoFilePathArr.count) {
            NSLog(@"揍你");
        }
        else {
            UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"是否删除照片"
                                                                                      message:@""
                                                                               preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction * cancelButton = [UIAlertAction actionWithTitle:@"取消"
                                                                    style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction *action) {
                                                                      NSLog(@"取消");
                                                                  }];
            UIAlertAction * creationBtn = [UIAlertAction actionWithTitle:@"删除"
                                                                   style:UIAlertActionStyleDestructive
                                                                 handler:^(UIAlertAction * _Nonnull action) {
                                                                     [_photoScrollView removeFromSuperview];
                                                                     _photoScrollView = nil;
                                                                     [self.photoFilePathArr removeObjectAtIndex:[removeIndexStr integerValue] - 1];
                                                                     if (_photoBtn.tag == 1000 + [removeIndexStr integerValue]) {
                                                                         [_photoBtn removeFromSuperview];
                                                                     }
                                                                     [self addPhoto];
                                                                     [self getPhotoInScrollView];
                                                                 }];
            [alertController addAction:cancelButton];
            [alertController addAction:creationBtn];
            [self presentViewController:alertController animated:YES completion:^{
                
            }];
        }
    }
}



-(NSMutableArray *)phothMuArray {
    if (_phothMuArray == nil) {
        _phothMuArray = [[NSMutableArray alloc] init];
    }
    return _phothMuArray;
}
-(NSMutableArray *)photoFilePathArr {
    if (_photoFilePathArr == nil) {
        _photoFilePathArr = [[NSMutableArray alloc] init];
    }
    return _photoFilePathArr;
}

-(NSMutableArray *)dataArr {
    if (_dataArr == nil) {
        _dataArr = [[NSMutableArray alloc] init];
    }
    return _dataArr;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
